import 'package:banyou_app/app/config/themes.dart';
import 'package:banyou_app/app/modules/home/controllers/home_controller.dart';
import 'package:banyou_app/app/modules/web/controllers/web_controller.dart';
import 'package:banyou_app/app/request/request_main.dart';
import 'package:banyou_app/app/routes/app_pages.dart';
import 'package:banyou_app/app/util/CupertinoLocalizations.dart';
import 'package:banyou_app/app/util/common_utils.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:shanyan/shanYanResult.dart';
import 'package:shanyan/shanyan.dart';
// import 'package:shanyan/shanYanResult.dart';
// import 'package:shanyan/shanyan.dart';

void main() async {
  await GetStorage.init();
  initConnectivityListener();

  // if (GetPlatform.isAndroid) {
  //   const SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
  //     statusBarColor: Colors.transparent,
  //     statusBarBrightness: Brightness.light,
  //     statusBarIconBrightness: Brightness.light,
  //     systemNavigationBarColor: Colors.transparent,
  //     // systemNavigationBarDividerColor: Colors.transparent,
  //     // systemNavigationBarDividerColor: Colors.white,
  //     systemNavigationBarIconBrightness: Brightness.light,
  //   );
  //   SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  // }
  // if (GetPlatform.isIOS) {
  //   const SystemUiOverlayStyle dark = SystemUiOverlayStyle(
  //       systemNavigationBarColor: Colors.transparent,
  //       systemNavigationBarIconBrightness: Brightness.light,
  //       statusBarIconBrightness: Brightness.light,
  //       statusBarBrightness: Brightness.light,
  //       statusBarColor: ColorConfig.app_main);
  //   SystemChrome.setSystemUIOverlayStyle(dark);
  // }
  box.write("qidong", true);
  runApp(const MyApp());

  _initChannel();
}

void initConnectivityListener() async {
  Connectivity().onConnectivityChanged.listen((event) {
    if (event == ConnectivityResult.mobile ||
        event == ConnectivityResult.wifi) {
      initSy();
      // EasyLoading.showToast('设备已经连接到网络');
    }
  });
}

initSy() async {
  // 初始化一键登录测试 com.253.QuanJu11 aj9SzHra
  // 初始化一键登 com.ycyinian.tgttravel JbUVLRmM
  // String appId = "aj9SzHra";
  String appId = "JbUVLRmM";
  ShanYanResult value = await OneKeyLoginManager().init(appId: appId);
  if (value.code == 1000) {
    ShanYanResult value1 = await OneKeyLoginManager().getPhoneInfo();
    if (value1.code == 1000) {
      box.write('oneKeyInit', true);
    } else {
      box.write('oneKeyInit', false);
    }
  } else {
    box.write('oneKeyInit', false);
  }
}

void _initChannel() {
  channel.setMethodCallHandler((call) {
    switch (call.method) {
      case "dfxusf_tokfn":
        {
          print(call.arguments);
          box.write("dfxusf_tokfn", call.arguments['dfxusf_tokfn']);
          return Future.value(1);
        }
      case "udea":
        {
          print(call.arguments);
          box.write("udea", call.arguments['udea']);
          return Future.value(1);
        }
      case "tdud":
        {
          print(call.arguments);
          box.write("tdud", call.arguments['tdud']);
          return Future.value(1);
        }
      case "location":
        {
          print(call.arguments);
          box.write("lng", call.arguments['lng']);
          box.write("lat", call.arguments['lat']);
          dynamic quan = box.read("quan");
          if (quan == "1") {
            Get.find<WebController>().showAddress.value = false;
            Get.find<WebController>().showAddress.refresh();
          } else {
            Get.find<HomeController>().showAddress.value = false;
            Get.find<HomeController>().showAddress.refresh();
          }

          return Future.value(1);
        }
      case "locationerror":
        {
          print(call.arguments);
          dynamic quan = box.read("quan");
          if (quan == "1") {
            Get.find<WebController>().showAddress.value = true;
            Get.find<WebController>().showAddress.refresh();
          } else {
            Get.find<HomeController>().showAddress.value = true;
            Get.find<HomeController>().showAddress.refresh();
          }
        }
    }

    return Future.value(0);
  });
}

class MyApp extends StatefulWidget {
  // const MyApp();
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint('应用程序可见并响应用户输入。');

        // var channel = MethodChannel("methodChannel");

        String mobile = box.read('mobile') ?? "";
        String oneKey = box.read('oneKey') ?? "";
        if (oneKey != '' || (mobile != '' && mobile != '16524285975')) {
          channel.invokeMethod('startLocation');
        }
        // channel.invokeMethod('startLocation');

        // RequestMain.getUrl({}, turl: 'http://servicef.hxhx.fun/sign/?a=my')
        //     .then((setData) {
        //   if (setData.isNotEmpty && setData['code'].toString() == "200") {
        //     if (setData['data'] is Map) {
        //       Map data = setData['data'];
        //       // 已满文案(为空可预约)
        //       box.write("full", data['full'] ?? "");
        //     }
        //   }
        // });
        // 获取设置
        RequestMain.getUrl({},
                turl: 'https://aqbanyou.olbibo.com.cn/sign/?a=my')
            .then((setData) {
          if (setData.isNotEmpty && setData['code'].toString() == "200") {
            if (setData['data'] is Map) {
              Map data = setData['data'];
              // 已满文案(为空可预约)
              box.write("full", data['full'] ?? "");
              // 应用市场好评弹窗 0:不弹,1:弹
              box.write("rank", data['rank'].toString());
              // 默认选择的tabbar
              box.write("tab", int.parse(data['tab'] ?? "0"));
              // 客服
              box.write("kefu", data['kefu'] ?? "");
              // 是否直接打开登录页
              box.write("prelogin", data['prelogin'].toString());
              // 判断接口中的quan，如果=1，直接跳转到接口中的find_url的h5页面，全屏展示，=0，还是当前的状态即可
              box.write("quan", data['quan'].toString());
              box.write("find_url", data['find_url'].toString());
            }
          }
        });

        break;
      // case AppLifecycleState.inactive:
      //   debugPrint('应用程序处于非活动状态，并且未接收用户输入');
      //   break;
      // case AppLifecycleState.paused:
      //   debugPrint('用户当前看不到应用程序，没有响应');
      //   break;
      // case AppLifecycleState.detached:
      //   debugPrint('该应用程序仍托管在颤振引擎上，但与任何主机视图分离');
      //   break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      return ScreenUtilInit(
        designSize: const Size(375, 812),
        builder: (context, _) => GetMaterialApp(
          debugShowCheckedModeBanner: false,
          title: '伴游',
          initialRoute: AppPages.INITIAL,
          getPages: AppPages.routes,
          theme: Themes.lightTheme,
          darkTheme: Themes.lightTheme,
          defaultTransition: Transition.cupertino,
          themeMode: ThemeMode.light,

          localizationsDelegates: const [
            CupertinoLocalizationsDelegate(),
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: [
            const Locale('zh', 'CN'),
            const Locale('en', 'US'), // English
          ],

          builder: EasyLoading.init(
            builder: (context, widget) {
              // ScreenUtil.setContext(context);
              return GestureDetector(
                onTap: () {
                  FocusScopeNode currentFocus = FocusScope.of(context);
                  if (!currentFocus.hasPrimaryFocus &&
                      currentFocus.focusedChild != null) {
                    FocusManager.instance.primaryFocus!.unfocus();
                  }
                },
                child: MediaQuery(
                  ///设置文字大小不随系统设置改变
                  data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                  child: GestureDetector(
                      // 全局回收键盘
                      onTap: () {
                        hideKeyboard(context);
                      },
                      child: widget),
                ),
              );
            },
          ),

          // home: HomePage(),
        ),
      );
    });
  }

  // 隐藏键盘
  void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }
}
